import { ApartmentOutlined, DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import ProCard from '@ant-design/pro-card';
import { PageContainer } from '@ant-design/pro-layout';
import { message, Menu, Button, Table, Input, Popconfirm, Space, Tag, Tooltip, } from 'antd';
import React, { useRef, useState } from 'react';
import { useIntl, useRequest } from 'umi';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
    getApiDataDictionaryCategorys as Categorys,
    getApiDataDictionaryCategoryDetailById as CategoryDetail,
    postApiDataDictionaryByIndexByLimitPagedList as PagedList,
    getApiDataDictionaryDetailByKey as Detail,
    deleteApiDataDictionary as Delete,
    deleteApiDataDictionaryByIdCategory as DeleteCategory,
} from '@/services/furion-cms/dataDictionary';
import styles from './index.less';
import DetailViewer from './components/dictionaryDetail';
import CategoryDetailViewer from './components/categoryDetail';
import PermissionsDefinition from '@/permissionsDefinition';
import { useCustomAccess } from '@/components/CustomAccess';

const DictionarySettings: React.FC = () => {
    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();
    const actionRef = useRef<ActionType>();
    const [selectedCategory, setSelectedCategory] = useState('all');
    const [tableParams, setTableParmas] = useState<Record<string, any>>();
    const [loadingVisible, handelLoadingVisible] = useState(false);
    const [categoryDeleteVisible, setCategoryDeleteVisible] = useState(false);

    const [details, setDetails] = useState<API.DataDictionaryDetailDto>();
    const [detailModalVisible, handleDetailModalVisible] = useState(false);

    const [categoryDetails, setCategoryDetails] = useState<API.DataDictionaryCategoryDetailDto>();
    const [categoryDetailModalVisible, handleCategoryDetailModalVisible] = useState(false);

    const { loading, data: CategoryList, refresh } = useRequest(Categorys, {
        loadingDelay: 500
    });

    const AccessButton = useCustomAccess(Button);
    const AccessConfirm = useCustomAccess(Popconfirm);

    const getDetails = async (key: string) => {
        handelLoadingVisible(true);
        try {
            const { data } = await Detail({ key });
            setDetails(data);
            handleDetailModalVisible(true);
        } catch { }
        handelLoadingVisible(false);
    }

    const getCategoryDetails = async (id: string) => {
        try {
            const { data } = await CategoryDetail({ id });
            setCategoryDetails(data);
            handleCategoryDetailModalVisible(true);
        } catch { }
    }

    const handlerDelete = async (keys: string[]) => {
        handelLoadingVisible(true);
        try {
            await Delete(keys);
            message.success(intl.formatMessage({
                id: 'pages.dictionary.delete.success',
                defaultMessage: '数据字典删除成功'
            }));
            actionRef.current?.reload();
        } catch { }
        handelLoadingVisible(false);
    }

    const columns: ProColumns<API.DataDictionaryDto>[] = [
        {
            title: intl.formatMessage({
                id: 'pages.dictionary.dataKey',
                defaultMessage: '标识名'
            }),
            dataIndex: 'dataKey',
            width: 200,
            sorter: true,
            search: false,
            fixed: 'left',
            copyable: true
        },
        {
            title: intl.formatMessage({
                id: 'pages.dictionary.category',
                defaultMessage: '类别'
            }),
            dataIndex: 'category',
            search: false,
            width: 120
        },
        {
            title: intl.formatMessage({
                id: 'pages.dictionary.dataValue',
                defaultMessage: '数据值'
            }),
            dataIndex: 'dataValue',
            search: false,
            render: (_, entity) => {
                const dataValues = entity.dataValue?.split(',') ?? [];
                if (dataValues.length > 1) {
                    return dataValues.map((item, index) => (<Tag key={`d_${index.toString()}`}>{item}</Tag>))
                }
                return _;
            },
            width: 150,
            ellipsis: true,
        },
        {
            title: intl.formatMessage({
                id: 'pages.dictionary.description',
                defaultMessage: '名称或描述'
            }),
            dataIndex: 'description',
            search: false,
            width: 150,
            ellipsis: true,
        },
        {
            title: intl.formatMessage({
                id: 'pages.user.createdTime',
                defaultMessage: '创建时间'
            }),
            dataIndex: 'createdTime',
            valueType: 'dateRange',
            sorter: true,
            width: 180,
            render: (dom, entity) => {
                return entity.createdTime;
            }
        },
        {
            title: intl.formatMessage({
                id: 'pages.searchTable.titleOption',
                defaultMessage: '操作'
            }),
            dataIndex: 'option',
            valueType: 'option',
            width: 200,
            fixed: 'right',
            render: (_, record) => [
                <AccessButton key="edit"
                    code={PermissionsDefinition.Dictionary.UpdateDictionary}
                    type="link" size="small"
                    onClick={() => getDetails(record.dataKey!)}>
                    {intl.formatMessage({
                        id: 'pages.common.update',
                        defaultMessage: '编辑'
                    })}
                </AccessButton>,
                <AccessConfirm key="del"
                    code={PermissionsDefinition.Dictionary.DeleteDictionary}
                    title={intl.formatMessage({
                        id: 'pages.common.delete.confirm',
                        defaultMessage: '您是否确认将「{name}」删除?'
                    }, {
                        name: record.dataKey
                    })}
                    onConfirm={() => handlerDelete([record.dataKey!])}
                >
                    <Button type="link" size="small"
                    >{intl.formatMessage({
                        id: 'pages.common.delete',
                        defaultMessage: '删除'
                    })}</Button>
                </AccessConfirm>
            ]
        }
    ];

    return (
        <PageContainer className={styles.main}
            breadcrumbRender={false}
            loading={loading}>
            <ProCard split="vertical">
                <ProCard colSpan="320px" title={<><ApartmentOutlined /> {intl.formatMessage({
                    id: 'pages.dictionary.category',
                    defaultMessage: '类别'
                })}</>} bodyStyle={{
                    padding: '18px 0'
                }}
                    extra={[
                        <AccessButton key="addCategory"
                            code={PermissionsDefinition.Dictionary.CreateCategory}
                            type="dashed" icon={<PlusOutlined />}
                            onClick={() => {
                                setCategoryDetails({ sortNumber: 0 });
                                handleCategoryDetailModalVisible(true);
                            }}
                        >{intl.formatMessage({
                            id: 'pages.dictionary.category.add',
                            defaultMessage: '添加类别'
                        })}
                        </AccessButton>
                    ]}
                >
                    <Menu mode="inline"
                        selectedKeys={[selectedCategory]}
                        onClick={({ key }) => {
                            setSelectedCategory(key);
                            setTableParmas({
                                ...tableParams,
                                categoryId: key === 'all' ? undefined : key
                            });
                        }}
                    >
                        <Menu.Item key="all">
                            {intl.formatMessage({
                                id: 'pages.dictionary.category.all',
                                defaultMessage: '全部'
                            })}
                        </Menu.Item>
                        {CategoryList?.map(m => (
                            <Menu.Item key={m.id}>
                                {m.name}
                                <Space style={{
                                    float: 'right',
                                    display: 'none'
                                }}>
                                    <AccessButton code={PermissionsDefinition.Dictionary.UpdateCategory}
                                        tooltip={intl.formatMessage({
                                            id: 'pages.common.update',
                                            defaultMessage: '编辑'
                                        })}
                                        type="link"
                                        icon={<EditOutlined />}
                                        onClick={() => getCategoryDetails(m.id!)} />
                                    <AccessConfirm
                                        code={PermissionsDefinition.Dictionary.DeleteCategory}
                                        title={intl.formatMessage({
                                            id: 'pages.common.delete.confirm',
                                            defaultMessage: '您是否确认将「{name}」删除?'
                                        }, {
                                            name: m.name
                                        })}
                                        onConfirm={async () => {
                                            try {
                                                await DeleteCategory({ id: m.id! });
                                                setSelectedCategory('all');
                                                setTableParmas({
                                                    ...tableParams,
                                                    categoryId: undefined
                                                });
                                                refresh();
                                                message.success(intl.formatMessage({
                                                    id: 'pages.dictionary.category.delete.success',
                                                    defaultMessage: '字典类别删除成功'
                                                }));
                                            } catch { }
                                        }}
                                        visible={categoryDeleteVisible}
                                        onVisibleChange={setCategoryDeleteVisible}
                                        destroyTooltipOnHide>
                                        <Tooltip title={intl.formatMessage({
                                            id: 'pages.common.delete',
                                            defaultMessage: '删除'
                                        })}>
                                            <Button type="link" icon={<DeleteOutlined />} onClick={() => setCategoryDeleteVisible(true)} />
                                        </Tooltip>
                                    </AccessConfirm>
                                </Space>
                            </Menu.Item>
                        ))}
                    </Menu>
                </ProCard>
                <ProCard bodyStyle={{
                    padding: 0
                }}>
                    <ProTable<API.DataDictionaryDto>
                        actionRef={actionRef}
                        loading={loadingVisible}
                        rowKey="dataKey"
                        columns={columns}
                        search={{ filterType: "light" }}
                        params={{ ...tableParams }}
                        request={(params, sort, filter) => {
                            // 表单搜索项会从 params 传入，传递给后端接口。
                            console.log(params, sort, filter);
                            handelLoadingVisible(true);
                            // 转换固定的参数
                            const { current, pageSize, createdTime } = params;
                            const [StartTime, EndTime] = createdTime || [];
                            // 删除无效参数
                            delete params.current;
                            delete params.pageSize;
                            delete params.createdTime;
                            return PagedList({
                                index: (current || 1),
                                limit: (pageSize || 10),
                                StartTime,
                                EndTime,
                                ...params
                            }, sort).then(result => {
                                const { list: data, total } = result.data || {};
                                return {
                                    data,
                                    success: result.success,
                                    total
                                }
                            }).finally(() => handelLoadingVisible(false));
                        }}
                        pagination={{
                            pageSize: 10,
                            showSizeChanger:true
                        }}
                        options={{
                            search: false,
                        }}
                        headerTitle={
                            <Input.Search key="search"
                                onSearch={(value) => setTableParmas({
                                    ...tableParams,
                                    keyword: value
                                })} allowClear />}
                        rowSelection={{
                            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                        }}
                        toolBarRender={() => [
                            <AccessButton code={PermissionsDefinition.Dictionary.CreateCategory}
                                type="primary"
                                key="create"
                                onClick={() => {
                                    setDetails({ sortNumber: 0 });
                                    handleDetailModalVisible(true);
                                }}>
                                创建字典
                            </AccessButton>
                        ]}
                        scroll={{
                            x: 800
                        }}
                    />
                    <DetailViewer
                        modalVisible={detailModalVisible}
                        recored={details}
                        onVisibleChange={handleDetailModalVisible}
                        onUpdate={() => actionRef.current?.reload()}
                    />
                    <CategoryDetailViewer
                        modalVisible={categoryDetailModalVisible}
                        recored={categoryDetails}
                        onVisibleChange={handleCategoryDetailModalVisible}
                        onUpdate={refresh}
                    />
                </ProCard>
            </ProCard>
        </PageContainer>
    )
}

export default DictionarySettings;